package com.tyut.controller;

import com.tyut.pojo.Student;
import com.tyut.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class StudentController {

    @Autowired
    private StudentService studentService;

    @RequestMapping("/addStudent")
    public String addStudent(Student student, Model model) {

        try {
            studentService.insertStudent(student);
            return "redirect:findStudentAll";
        }catch(Exception e) {
            e.printStackTrace();
            model.addAttribute("msg", "添加失败!");
            return "failed";
        }
    }

    @RequestMapping("/editById")
    public String editById(String id, Model model) {

        try {
            Student student = studentService.findStudentById(id);
            model.addAttribute("student",student);
            return "edit";
        }catch(Exception e) {
            e.printStackTrace();
            return "failed";
        }
    }

    @RequestMapping("/editStudent")
    public String editStudent(Student student, Model model) {

        try {
            studentService.updateStudent(student);
            return "sm1";
        }catch(Exception e) {
            e.printStackTrace();
            model.addAttribute("msg","修改失败！");
            return "failed";
        }
    }

    @RequestMapping("/findStudentById")
    public String findStudentById(String id, Model model) {

        Student student = studentService.findStudentById(id);
        model.addAttribute("student",student);
        return "sm1";

    }

    @RequestMapping("/findStudentByName")
    public String findStudentByName(HttpServletRequest request, Model model) {
        String name = request.getParameter("name");
        List<Student> student = studentService.findStudentByName(name);
        model.addAttribute("list",student);
        return "sm2";
    }

    @RequestMapping("/findStudentAll")
    public String findStudentAll(HttpServletRequest request,Model model) {
        List<Student> studentAll = studentService.findStudentAll();
        model.addAttribute("list",studentAll);
        return "studentmessage";
    }

    @RequestMapping("/sm1JSP")
    public String sm1JSP(){
        return "sm1";
    }
    @RequestMapping("/sm2JSP")
    public String sm2JSP(){
        return "sm2";
    }
    @RequestMapping("/smAddJSP")
    public String smaddJSP(){
        return "smadd";
    }

}
